






import { i18nMixin, storeMixin, moduleMixin, renderV2ComponentMixin, windowResizeMixin, clickMixin } from './mfc-mixin.js'





import './mfc.config.js'
// import bizConfig from '../mfc_comps/mfc-biz-config.js?v1'

// import './less-4.1.3.js'



let mfcModeFullPathMap = {

}

let debugTimeStamp=Date.now()
    let debugTimeDuration=0;
    function updateDebugTimeStamp(){
        debugTimeDuration=Date.now()-debugTimeStamp
        // console.log('durationnnnnnnnnnn--:',debugTimeDuration);
        debugTimeStamp=Date.now()
    }

let mountDomClock;
let mfcRouterAdapterInvokedCount=0;
let allowFetchTargetRoutePath = true;
let targetRoutePath = ''
let allowMount = true;
let last$=null;
globalThis.mfcRouterAdapter = {
  template: `<div>
      <div ref="el">
        <div id="flag"></div>
          
      </div>
  </div>`,
  async mounted() {
    // console.log('this in mounted--:',this)


    // if(!allowMount){
    //   return false;
    // }
    // allowMount = false;
    // setTimeout(() => {
    //   allowMount = true;
    // }, 50)

    // let previousallowFetchTargetRoutePath=allowFetchTargetRoutePath

    // let path;
    if (allowFetchTargetRoutePath) {
      targetRoutePath = new Array(2).fill($v3.$route.path).join('').slice(1)
      allowFetchTargetRoutePath = false;
    }
    setTimeout(() => {
      allowFetchTargetRoutePath = true;
    }, 130)




    // let wm=new WeakMap();

    // console.log()
    let el = this.$el
    // wm.set(el,true)

    // debugger;
    let router = MFCRouter.useRouter();
    let route = MFCRouter.useRoute()
    // console.log('router--:',route,router)
    // MFC.onMounted(()=>{
    el.id = 'el_' + Math.random() * 10000000000000000000
    el.id = el.id.replace('.', '')
    // console.log('el--:',el)

    // console.log('targetRoutePath--:', targetRoutePath)
    let path = targetRoutePath;
    // let path = router.currentRoute._value.meta.mfcPath
    // let path=new Array(2).fill($v3.$route.path).join('').slice(1)
    // debugger;

    let fn = () => {

      console.log('mounted', path)
      return window.$v3.$mountMfcComponent('#' + el.id,
        path.split('/').slice(1).join('/'),
        {

        },
        path.split('/')[0] || ''
        , false
        , false
      )

    }
    updateDebugTimeStamp()
      let obj$=document.getElementById(el.id)
      // console.log('obj$---:',obj$,obj$.innerHTML.trim())
      if (true) {
        mfcRouterAdapterInvokedCount++;
      // if (obj$) {
        // console.log('will invoke fn',debugTimeDuration,'durationnnnnnnnnnn---')
        // if(mfcRouterAdapterInvokedCount>1 && debugTimeDuration>=500){
        //   return false;
        // }


        // if(!allowFetchTargetRoutePath){
        //   return false;
        // }
        let $;

        // if(last$){
        //   $=last$;
        //   setTimeout(()=>{
        //     last$=null;
        //   },150)
        // }else{
        //   $ = await fn()
        // }


        $ = await fn()
        // let previousAllowMount=allowMount
        
        // console.log('$---:',$)

        // alert('mounted')

        // alert($._component._isMFCMode)
        // if($._component._isMFCMode && !mfcModeFullPathMap[path]){

        //   mfcModeFullPathMap[path]=true;
        //   $.mount('#'+el.id);
        //   window.$v3.$bus.$emit('B_ROUTE_COMP_RENDERED',router.currentRoute._value)
        // }else{
        //   // alert(11)
        //   $.mount('#'+el.id);
        //   window.$v3.$bus.$emit('B_ROUTE_COMP_RENDERED',router.currentRoute._value)
        // }

        // if(previousAllowMount){
        $.mount('#' + el.id);
        setTimeout(() => {
          window.$v3.$bus.$emit('B_ROUTE_COMP_RENDERED', router.currentRoute._value)
        })
        // }




        // if(true){
        //   $.mount('#'+el.id);
        // }


        // })
      }
      // console.log('el--:',el,el.id,document.getElementById(el.id))
    // }, 100+(Math.random()*10))

  }
}





let bizConfig = globalThis.mfcBizConfig;

if (!String.prototype.replaceAll) {
  String.prototype.replaceAll = function (s1, s2) {
    return this.replace(new RegExp(s1, "gm"), s2)
  }
}


let mitt = (function () {
  let myModule = {};
  myModule.exports = function (n) {

    return {
      all: (window._MITT_EVENTS = (n = n || new Map)),

      on: function (e, t) { var i = n.get(e); i ? i.push(t) : n.set(e, [t]) },

      off: function (e, t) { var i = n.get(e); i && (t ? i.splice(i.indexOf(t) >>> 0, 1) : n.set(e, [])) },

      emit: function (e, t) { var i = n.get(e); i && i.slice().map(function (n) { n(t) }), (i = n.get("*")) && i.slice().map(function (n) { n(e, t) }) }
    }
  };
  return myModule.exports;

})();

// import mitt from './mitt.js'

// import {unmountV3App,mountV3App} from './mfc-bootstrap.js'







export const ready = Promise.resolve().then(async () => {
  let result = _loadJS(bizConfig.mfcLibPath)

  

  // await bizConfig.useMfcRouter?_loadJS(bizConfig.mfcRouterLibPath):Promise.resolve()
  await result;
  $v3.$store=MFC.reactive($v3.$store)
  if (bizConfig.useMfcRouter) {
    await _loadJS(bizConfig.mfcRouterLibPath);

  }
  return result;
})

export const v3BootstrapPromiseFn = () => import('./mfc-bootstrap.js')

  // let v3BootstrapPromiseFn = () => import('./mfc-bootstrap.js')

  ; (async function () {
    await ready;
    let { unmountV3App, mountV3App, loadMfcDeps, mountMFCComp, handlePushState } = (await v3BootstrapPromiseFn()).default;

    window.$v3.$unmountV3App = unmountV3App;
    window.$v3.$mountMfcComponent = mountMFCComp;
    // window.$v3.$mountMfcComponent = (domNodeSelector, compName, vm, dir) => {


    //   return new Promise((resolve)=>{
    //     // window.$v3.$mountMfcComponent = (domNodeSelector, compName, vm, cb, dir) => {
    //   // domNodeSelector = domNodeSelector || '#mfc-page-container'

    //   // useEffectFn(()=>{
    //   // let {unmountV3App,mountV3App}=v3Bootstrap
    //   // window.$v3.doNothing('mountV3App---:',mountV3App)

    //   // let resolver;
    //   setTimeout(async () => {

    //     // window.$v3.doNothing('elllllllllllll',document.querySelector(domNodeSelector))
    //     // let domNode=document.querySelector(domNodeSelector)
    //     // window.$v3.doNothing(11111)


    //     await mountMFCComp(domNodeSelector, compName, {
    //       ...vm
    //     }, dir)
    //     resolve();
    //     // alert('333')
    //     // if (typeof (cb) == 'function') {
    //     //   cb()
    //     // }
    //     // .then((res)=>{
    //     //   resolver
    //     // })
    //   })
    //   // },600)

    //   // return ()=>{
    //   //   window.$v3.doNothing(222222)
    //   //   // alert('will unmount')
    //   //   unmountV3App(vm)
    //   // }


    //   // },[])
    //   })
    // }
    // debugger;

    setTimeout(() => {
      if (routerPageContainerSelector) {
        // window.$v3.doNothing('routerPageContainerSelector--:',routerPageContainerSelector)


        var pushState = window.history.pushState;
        // var popState=history.popState;
        window.history.pushState = function (state, title, nextUrl) {
          handlePushState(nextUrl)
          window.$v3.doNothing('push state invoked', nextUrl)
          // window.$v3.doNothing('push state args--:', arguments)
          pushState.apply(history, arguments);
          window.$v3.bizConfig.forceUpdateSidebarMenuClass()
        };

        window.addEventListener('popstate', function (event) {
          window.$v3.doNothing('pop state invoked', location.pathname)
          handlePushState(location.pathname)
          window.$v3.bizConfig.forceUpdateSidebarMenuClass()

        });
        window.document.body.addEventListener('click', (e) => {

          if (window.$v3.bizConfig.forceUpdateSidebarMenuClassTrigger.find(s => e.target.closest(s))) {
            setTimeout(() => {
              window.$v3.bizConfig.forceUpdateSidebarMenuClass()
            })
          }

          // if(e.target.closest('li.ant-menu-submenu')){
          //   setTimeout(()=>{
          //     window.$v3.bizConfig.forceUpdateSidebarMenuClass()
          //   })
          // }
        })

        setTimeout(() => {
          handlePushState(location.pathname)
        })
        // appendAppDiv()
      }
    })

  })();




var _loadJS = (function () {

  let cacheedScriptUrls = []
  return function (url, cache = true, win) {
    return new Promise(async (resolve) => {
      if (!url) {
        resolve();
        return false;
      }

      if (cacheedScriptUrls.includes(url)) {
        resolve();
        return
      }

      await window.eval(`new Promise(async (resolve)=>{

        await import('${url}');
        resolve();
      })`);
      resolve();


      // let doc = win ? win.document : document;
      // let targetNode = doc.body;

      // var scriptTag = doc.createElement("script");


      // scriptTag.src = url;
      // scriptTag.type = "text/javascript";

      // scriptTag.onload = function () {
      //   cache && cacheedScriptUrls.push(url)
      //   resolve();
      // };

      // targetNode.appendChild(scriptTag);

    });
  };
})();







let mittInstance = new mitt()


const $bus = {}

// const emitter = mitt()

$bus.$on = mittInstance.on

$bus.$emit = mittInstance.emit

$bus.$off = mittInstance.off

window.$v3 = {
  bizConfig: bizConfig,
  doNothing: () => { },
  switchV2KeepAlive() {
    let v = localStorage.getItem('useKeepAlive')
    if (v) {
      localStorage.removeItem('useKeepAlive')
    } else {
      localStorage.setItem('useKeepAlive', 1)
    }

    location.reload();
  },
  $bus: $bus,
  appLang: null
}




function handleEs6Template(strings, restArgs) {
  let res = ''
  for (let i = 0; i < 10000; i++) {
    // res += strings[i] + (restArgs[i] || '')
    res += (strings[i] || '') + (restArgs[i] || '')
    if (!strings[i] && !restArgs[i]) {
      break;
    }
  }

  return res
}

window.$v3.html = window.html = (strings, ...restArgs) => {

  let res = handleEs6Template(strings, restArgs)

  return res;

};
window.$v3.createGlobalStyle = function (strings, ...restArgs) {
  let res = handleEs6Template(strings, restArgs)

  return res;
  // return '$$ ' + res;
};

// let v3Store = {
//   currentActive: '1'
// }


window.$v3.$store = window.$$store
// window.$v3.$store = v3Store

export const store = window.$$store;
// export const store = v3Store;

// window.$v3.doNothing('API_REQUEST--:',API_REQUEST)
// window.$v3.API_REQUEST=API_REQUEST;




window.$v3.$typeof = function () {
  return typeof (arguments[0])
}
window.$v3.$mixins = {
  clickMixin,
  windowResizeMixin,
  i18nMixin,
  // optionsApiDebugMixin,
  storeMixin,
  // printMixin,
  moduleMixin,
  renderV2ComponentMixin

}
// window.$v3.echarts=echarts;
// let BASE_URL=process.env.xxxxxxxxxxxxx

// if(!BASE_URL.startsWith('http:') && !BASE_URL.startsWith('https:') && !BASE_URL.startsWith('//')){
//     if(location.hostname=='127.0.0.1' && BASE_URL.startsWith('/')){
//         BASE_URL="http://127.0.0.1:3001"+BASE_URL
//     }
// }

// window.$v3.PROCESS_ENV={
//     BASE_URL
// }

window.$v3.$bus.$on('B_APP_SET_LANG', (val) => {
  window.$v3.appLang = val;
})





// export default function ready(cb){
//     if(typeof(cb)=='function'){
//         cb(window.$v3)
//     }
// }
// alert('test')
// window.$v3.doNothing('ttt')



var u;
let cacheMap = {

}
window.$v3.mfcFileCaches = cacheMap
let httpGet = function (url, useCache = false) {

  if (url.startsWith('./') && window._isMfcNestedInOtherProject && window._IS_LOCAL_HOST) {
    url = 'http://127.0.0.1:3009/' + url
  }

  // window.$v3.doNothing("url in http get--:",url,cacheMap)


  return new Promise(async (resolve, reject) => {
    if (window.$v3.mfcFileCaches[url]) {
      resolve(window.$v3.mfcFileCaches[url]);
      return false;
    }


    let nowTime = window.$v3.appHash
    // let nowTime = u.formatTime(null, true)

    let randomStr = "jsx html css less sass scss js json veact mfc"
      .split(" ")
      .find((s) => url.endsWith("." + s))
      ? nowTime
      : Math.random();

    let _url = url + "?r=" + (randomStr)
    _url = _url.replace("??", '?')
    try {
      let txt = (await (await fetch(_url, { mode: 'cors' })).text())
      if (useCache && !window.$v3.mfcFileCaches[url]) {
        window.$v3.mfcFileCaches[url + '?date=' + window.$v3.$utils.formatTime(null, true)] = txt
      }
      resolve(txt);
    } catch (e) {
      reject({
        e: e,
        message: "加载" + url + "错误",
      });
    }

    // var httpRequest = new XMLHttpRequest();
    // httpRequest.open(
    //   "GET",
    //   url + "?r=" + (randomStr),
    //   true
    // );
    // httpRequest.send();
    // /**
    //  * 获取数据后的处理程序
    //  */
    // httpRequest.onreadystatechange = function () {
    //   if (httpRequest.status != 200) {
    //     if (httpRequest.readyState == 4) {
    //       reject({
    //         httpRequest: httpRequest,
    //         message: "加载" + url + "错误",
    //       });


    //     }


    //   } else {
    //     if (httpRequest.readyState == 4) {
    //       if(useCache && !window.$v3.mfcFileCaches[url]){
    //         window.$v3.mfcFileCaches[url+'?date='+window.$v3.$utils.formatTime(null,true)]=httpRequest.responseText
    //       }
    //       resolve(httpRequest.responseText);
    //     }
    //   }
    // };
  });
}

u = {
  sleep(timeout = 0) {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve()
      }, timeout)
    })
  },
  poll(fn) {
    return new Promise((resolve) => {
      let loop = () => {
        if (fn()) {
          resolve();
        } else {
          setTimeout(() => {
            loop();
          }, 20)
        }
      }

      loop();
    })

  },
  isDevServer() {
    // return false;
    return location.hostname == '127.0.0.1' || location.hostname == 'localhost'
  },
  sequenceExecPromiseArr: (function () {

    let fun = function (arr) {
      return new Promise((resolve) => {

        if (!arr.length) {
          resolve()
          return false;
        }
        let finalRes = []
        arr.forEach((item, index) => {
          arr[index] = [].concat(item).flat()
        })
        let len = arr.length;
        let index = -1;

        let singleExec = async () => {
          if (fun.__PENDING instanceof Promise) {
            await fun.__PENDING
          }
          index++;
          let item = arr[index];
          item.forEach((row, index) => {

            if (typeof (row) == 'function') {

              // console.log('fun row--:',row)
              // alert('yes')
              item[index] = row()
            }
          })
          // console.log('item---:',item,typeof(item))
          let theRes = await Promise.all(item);
          finalRes.push(theRes.length == 1 ? theRes[0] : theRes)
          if (index != len - 1) {
            setTimeout(() => {
              setTimeout(() => {
                singleExec()
              })
              // singleExec()
            })
            // },30)

          } else {
            resolve(finalRes)
          }
        }

        singleExec()

      })
    }
    return fun;
  })(),
  _loadJS: _loadJS,
  httpGet: httpGet,//
  formatTime(date, hmdOnly = false) {
    date = date || new Date();
    let t = date.getTime();
    if (typeof t == "number" && window.isNaN(t)) {
      return "";
    }

    let d = new Date(date);

    var yyyy = d.getFullYear().toString();
    var mm = (d.getMonth() + 1).toString();
    var dd = d.getDate().toString();
    var hh = d.getHours().toString();
    var ii = d.getMinutes().toString();
    var ss = d.getSeconds().toString();

    let res =
      yyyy +
      "-" +
      (mm[1] ? mm : "0" + mm[0]) +
      "-" +
      (dd[1] ? dd : "0" + dd[0]);
    if (!hmdOnly) {
      res +=
        " " +
        (hh[1] ? hh : "0" + hh[0]) +
        ":" +
        (ii[1] ? ii : "0" + ii[0]) +
        ":" +
        (ss[1] ? ss : "0" + ss[0]);
    }

    return res;
  },


}


window.$v3.$utils = u;

window.$v3.appHash = u.formatTime(null, true) + '__' + Math.random()
if (window.$v3.$utils.isDevServer()) {
  window.$v3.appHash += '____' + Math.random()
  window.$v3.$bus.$on('B_HMR', () => {
    window.$v3.appHash = window.$v3.appHash.split('____')[0] + '____' + Math.random()
  })
  // window.$v3.localMode=true;
} else {
  // window.$v3.localMode=false;
}

window.$v3.$apps = []

// let $lastPage = {

// }

let routerPageContainerSelector = bizConfig.routerPageContainerSelector






// export const flyPageByLocationPath = handlePushState;
export const setGlobalPropsForMfcComponents = (providedVariablesForMfc) => {







  window.$v3.bizConfig.providedVariablesForMfc = providedVariablesForMfc


}

window.$v3.setGlobalPropsForMfcComponents$ = setGlobalPropsForMfcComponents;


if (typeof (module) != 'undefined') {
  module.exports = {}
}



// export const v3Utils=u;//